<?php

namespace common\helpers;

use yii\helpers\Url;
use yii\base\UserException;

class Util {

    /**
     * 输出对象
     * @param all $rows     需要输出的对象
     * @param bool $type    以print_r还是var_dump来输出
     * @param bool $exit    输出后是否中止
     */
    public static function pr($rows, $type = false, $exit = false) {
        echo '<pre>';
        $type ? var_dump($rows) : print_r($rows);
        echo '</pre>';
        $exit && exit();
    }

    /**
     * 将一维数组转为 sql condition 字符串 (['a' => 1, 'b' => 2, 'c => '+1'] To: a=1, b=2, c=c+1)
     * @param array 需要转换的数组对象
     * @return string
     */
    public static function arrayToStr(array $datas = []) {
        $str = '';
        if (!empty($datas)) {
            $s = array('like', 'update', 'id', 'key', 'starting');

            $i = 1;
            $dataCount = count($datas);
            foreach ($datas as $key => $data) {
                $str .= (in_array($key, $s) ? '`' . $key . '`' : $key) . ($data && in_array($data, array('?+1', '?-1', '?+2', '?-2')) ? '=' . $key . strtr($data, array('?' => NULL)) : '=\'' . mysql_escape_string($data) . '\'') . ($i < $dataCount ? ', ' : NULL);
                $i++;
            }
        }
        return $str;
    }

    public static function exportXml($filename, $title, $data) {
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment; filename={$filename}.xls");
        header('Pragma: no-cache');
        header('Expires: 0');

        echo iconv('utf-8', 'GB2312//IGNORE', implode("\t", $title)), "\n";
        foreach ($data as $value) {
            echo iconv('utf-8', 'GB2312//IGNORE', implode("\t", $value)), "\n";
        }

        exit();
    }

    public static function exportCsv($filename, $title, $data) {
        $str = '';
        $str .= iconv('utf-8', 'gb2312', implode(",", $title)) . "\n";
        foreach ($data as $value) {
            $str .= iconv('utf-8', 'gb2312', implode(",", $value)) . "\n";
        }
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $str;
        exit();
    }

    /**
     * 用户IP
     */
    public static function getUserIP() {
        if (!\Yii::$app instanceof \yii\web\Application) {
            return "192.168.0.1";
        }
        $ip = \Yii::$app->getRequest()->getUserIP();

        if (strstr($ip, ",")) {//含有逗号
            $a = explode(",", $ip);
            return trim($a[1]);
        } else if (empty($ip) || strstr($ip, ":")) {
            return "192.168.0.1";
        } else {
            return $ip;
        }
    }

    /**
     * 用户真实IP
     */
    public static function getUserRealIP($type=1) {
        if(!\Yii::$app instanceof \yii\web\Application){
            return "192.168.0.1";
        }
        $realip = '';
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]){
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_X_REAL_IP"]) && $_SERVER["HTTP_X_REAL_IP"]) {
                $realip = $_SERVER["HTTP_X_REAL_IP"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"]) && $_SERVER["HTTP_CLIENT_IP"]) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_X_REAL_IP")) {
                $realip = getenv("HTTP_X_REAL_IP");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        if($type && strstr($realip, ",")) {//含有逗号
            $a = explode(",", $realip);
            return trim($a[0]);
        }
        return $realip;
    }

    public static function checkSmsAttack($type){
        $ip = Util::getUserRealIP();
        // 白名单IP
        $permit_ip_list = [
            '118.190.76.163', // 借款大师
            '183.63.252.239', // 速易渠道
        ];
        if (in_array($ip, $permit_ip_list)) {
            return true;
        }

        $time = time();
        $last_ip_cache_key = date('Ymd',$time-86400).'-'.$type.'-'.$ip;
        $ip_cache_key = date('Ymd',$time).'-'.$type.'-'.$ip;
        $times = \Yii::$app->redis->get($last_ip_cache_key) >= 1000 ? \Yii::$app->redis->get($last_ip_cache_key) : 1;
        $count = \Yii::$app->redis->incr($ip_cache_key);
        \Yii::$app->redis->expire($ip_cache_key, 86400);
        if($count >= 1000){
            throw new UserException('发送频率过多，如有疑问，请联系客服');
        }
        $black_ips = ['115.210.75.0','218.66.222.32','58.57.0.178','123.126.152.18','61.149.184.65','101.81.122.230','218.87.138.43','183.24.167.66','183.39.91.111','183.39.90.205','113.116.25.42','14.156.229.197','182.99.139.73','14.156.229.166','58.22.71.196','223.74.135.251','59.58.6.60','123.118.98.110','106.39.143.205','223.74.248.84','183.38.250.15','27.219.36.132','61.130.31.0','182.43.109.255','171.221.217.53','115.171.21.120','14.156.231.245','223.74.200.205','123.123.96.38','27.47.19.102','36.111.131.124','117.24.165.14','115.234.73.141','58.217.163.172','113.232.114.37','14.124.174.3','49.70.48.247','118.212.84.91','116.231.218.106','113.69.137.190','27.159.245.153','119.125.9.254','59.172.157.68','123.121.192.11','183.24.166.214','113.195.66.238','119.125.8.159','119.125.11.7','223.243.246.170','123.184.33.196','118.114.224.53','125.108.102.96','112.109.208.10','59.50.232.239','101.24.21.186','183.71.209.23','175.31.47.237','123.207.11.46','175.31.46.48','36.248.248.10','61.154.103.17','120.192.92.109','119.29.152.160','106.6.79.241','14.158.51.94','183.27.180.40','183.4.43.58','36.248.245.46','125.93.108.199','182.99.139.164','113.111.81.109','223.74.135.156','182.108.95.66','36.249.181.130','119.125.70.208','120.209.63.30','125.115.42.184','221.239.28.140','123.121.205.32','120.92.80.244','116.228.6.130','36.5.104.243','183.165.237.90','113.250.238.195','36.249.133.66','180.105.57.253','110.83.43.19','183.24.167.247','125.112.204.152','60.162.237.68','49.4.142.207','211.95.3.19','113.82.33.106','120.77.148.174','60.181.110.40','222.76.57.30','120.192.92.105','113.82.32.70','59.45.170.140','139.199.156.96','218.10.97.91','59.56.115.180','125.121.65.2','222.76.172.11','14.220.230.66','144.0.51.125','223.73.255.208','220.184.126.142','219.137.139.161','110.88.209.40','223.72.250.35','119.29.114.246','171.212.201.215','221.208.196.195','124.234.172.98','116.231.183.67','175.7.35.63','120.43.85.106','61.132.225.115','120.40.97.107','123.149.16.105','123.184.32.30','119.125.52.90','49.70.7.147','14.124.189.226','120.37.169.164','183.25.56.177','211.143.45.151','114.238.63.61','58.208.250.36','42.48.158.8','106.226.9.139','175.18.57.118','111.47.123.101','120.92.82.107','111.47.203.207','117.175.140.141','183.60.162.153','223.74.117.83','182.114.212.84','110.180.34.229','122.234.181.160','222.161.244.174','183.239.55.14','118.192.104.28','180.117.161.51','117.92.13.248','61.164.201.234','203.156.236.130','27.156.39.9','115.223.249.88','175.7.34.178','220.180.238.25','120.84.10.225','123.207.170.136','223.74.135.230','36.63.155.142','210.79.88.75','111.47.203.217','59.44.136.195','183.148.230.77','47.52.19.247','119.4.255.9','122.235.128.254','120.27.217.104','223.74.251.140','59.42.120.93','122.114.190.87','119.54.152.183','223.74.135.227','110.184.221.150','223.74.251.5','36.7.64.53','223.74.248.113','112.83.25.249','111.38.189.251','112.83.24.17','114.112.124.74','115.193.213.27','120.37.113.223','14.220.231.49','113.120.40.230','223.74.251.74','210.83.81.73','122.114.168.4','122.235.175.129','58.59.214.199','58.217.135.203','222.172.173.157','222.173.25.138','211.95.3.18','59.58.19.164','123.249.57.54','111.47.123.106','61.172.253.8','115.213.242.138','61.172.235.158','120.37.152.91','124.134.11.190','223.74.135.179','218.6.125.149','14.211.202.2'];
        if (in_array($ip, $black_ips)) {
            throw new UserException('发送频率过高');
        }
        $user_agent = \Yii::$app->getRequest()->getUserAgent();
        if ($user_agent == 'Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)') {
            throw new UserException('发送频率过高，请稍后再试');
        }
        return true;
    }

    /**
     * 用户类型
     */
    public static function getClientType() {

        if (@$_SERVER['SERVER_NAME'] == 'm.koudaikj.com') {
            return 'wap';
        } else {
            if (method_exists(\Yii::$app->getRequest(), 'getClient')) {
                $client = \Yii::$app->getRequest()->getClient();

                return $client->clientType;
            } else {
                return "pc";
            }
        }
    }

    /**
     * 验证手机
     */
    public static function verifyPhone($phone) {
        return preg_match('/^1[0-9]{10}$/', $phone);
    }

    /**
     * 验证身份证号
     */
    public static function verifyIdNumber($id_number) {
        return preg_match('/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $id_number) || preg_match('/^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$/', $id_number);
    }


    public static $_config = [];

    /**
     * 载入配置文件
     * @param $name as (@mobile/test,@frontent/test,test)
     * 例子:Util::loadConfig('@frontend/test'),Util::loadConfig('test')
     *
     */
    public static function loadConfig($name) {
        if (!isset(self::$_config[$name])) {
            if (!strncmp($name, '@', 1)) {//use an alias
                $pos = strpos($name, '/');
                $root = \Yii::getAlias(substr($name, 0, $pos)) . '/config';
                $configFilePath = $root . substr($name, $pos);
            } else if (strpos($name, '/') || strpos($name, '\\')) {
                $configFilePath = realpath($name);
            } else {
                $configFilePath = \Yii::$app->getBasePath() . DIRECTORY_SEPARATOR . 'config/' . $name;
            }
            $configFilePath = $configFilePath . '.php';
            if (!file_exists($configFilePath)) {
                throw new \yii\base\Exception('load config data ' . $name . ' failed');
            }
            self::$_config[$name] = require($configFilePath);
        }
        return self::$_config[$name];
    }


    /**
     * 信用卡app根据借款天数和金额,计算服务费
     * @param unknown $period
     * @param unknown $money
     */
    public static function calcNoCreditLoanInfo($period,$money){
        $counter_fee = 0;
        if ($period <= 14) {
            $counter_fee = sprintf("%d",$money * 0.10);
        }else{
            $counter_fee = sprintf("%d",$money * 0.10);
        }
        return $counter_fee;
    }

    /**
     * 大写金额转换
     */
    // 阿拉伯数字转中文大写金额
    public static function numToMoney($num) {
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int) $num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }
        $j = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c = $left . $right;
                $j = $j - 3;
                $slen = $slen - 3;
            }
            $j = $j + 3;
        }
        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }
        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }
    }

    /**
     * 获取活动配置
     * @param unknown $key
     * @return mixed
     */
    public static function getActInfos($key) {
        $info = \Yii::$app->params[$key];
        $time = time();
        if ($info && isset($info['start_time']) && isset($info['end_time']) && $time >= strtotime($info['start_time']) && $time <= strtotime($info['end_time'])) {
            return \Yii::$app->params[$key];
        }
        return [];
    }

    /**
     * 获取零钱包贷款期限
     */
    public static function getLqbLoanPeriod() {
        $info = self::getActInfos('ygd_act_national_day');
        $now = time();
        if ($now >= strtotime("2017-01-11 00:00:00") && $now <= strtotime("2017-01-16 23:59:59")) {
            return 7;
        }elseif ($now >= strtotime("2017-01-17 00:00:00") && $now <= strtotime("2017-01-19 23:59:59")) {
            return 21;
        }elseif ($now >= strtotime("2017-01-20 00:00:00") && $now <= strtotime("2017-01-27 23:59:59")) {
            return 14;
        }
        if($info && isset($info['day'])){
            return $info['day'];
        }
        return 14;
    }

    /**
     * 生成页面顶部面包屑
     * @param array $menu
     * @param int $select_idx 高亮选项
     * @param string $get 附加上get参数
     * @return array
     */
    public static function getBreadCrumbsMenu(array $menu, $select_idx, $get = false) {
        $param = ($get) ? \Yii::$app->request->get() : [];

        foreach ($menu as &$_item) {
            $_item[1] = \is_array($_item[1]) ? $_item[1] : [ $_item[1]];
            $_item[1] = Url::toRoute(\array_merge($_item[1], $param));
            $_item[2] = 0;
        }

        //选中某个menu
        $menu[$select_idx][2] = \intval(isset($menu[$select_idx][2]));

        return $menu;
    }

    /**
     * 根据不同的渠道商，返回不同的不同的文字
     * @param unknown $key
     * @param string $channel
     */
    public static function t($key, $channel = '') {
        $channel = empty($channel) ? self::getChannelCode() : $channel;

        $name = 'm';
        if(!empty($channel)){
            $name = $name.'_'.$channel;
        }
        if('haojie' === $channel){
            $name = 'm';
        }
        $config = self::loadConfig('@common/message/'.$name);
        if(isset($config[$key])){
            return $config[$key];
        }
        return '';
    }

    /**
     * 获取当前请求对应的渠道编码
     * @return string 渠道编码，默认好借
     */
    public static function getChannelCode(){
        $channel = 'haojie';
        if (\Yii::$app instanceof \yii\web\Application) {
            if (\Yii::$app->controller->isFromHaojie()) {
                $channel = 'haojie';
            } elseif (\Yii::$app->controller->isFromXjk()) {
                $channel = 'kdxj';
            }
        }
        return $channel;
    }

    /**
     * 获取当前请求对应的版本号
     * @return string 渠道编码
     */
    public static function getVersion(){
        return \Yii::$app->controller->getClientVersion();
    }

    /**
     * 解析身份证获取年龄
     * @param LosnPerson $user
     * @return int
     */
    public static function getAge($id_number){
        $now = intval(date('Y',time()));
        $id_card_len = strlen($id_number);
        if($id_card_len == 18){
            $year = (int)substr($id_number,6,4);
            $age = $now - $year;
        }elseif($id_card_len == 15){
            $year = "19" . substr($id_number,6,2);
            $age = $now - $year;
        }else{
            $age = 0; //身份证解析失败
        }
        return $age;
    }

    /**
     * 解析身份证获取年龄(周岁)
     * @param LosnPerson $user
     * @return int
     */
    public static function getFullAge($id_number){
        $id_card_len = strlen($id_number);

        if ($id_card_len == 18) {
            $birthday = substr($id_number,6,8);
        } elseif ($id_card_len == 15) {
            $birthday = "19" . substr($id_number,6,6);
        } else {
            return 0;
        }

        $birthday = strtotime($birthday);

        $age = date('Y', time()) - date('Y', $birthday) - 1;

        if(date('m', time()) < date('m', $birthday))
        {
            return $age;
        }

        if(date('m', time()) > date('m', $birthday) || date('d', time()) > date('d', $birthday))
        {
            $age += 1;
        }

        return $age;
    }

    /**
     * 多维数组多个字段排序（类似于SQL排序）
     * @param LosnPerson $user
     * @return int
     */
    public static function sortArrByManyField()
    {
        $args = func_get_args();
        if(empty($args)){
            return null;
        }
        $arr = array_shift($args);
        foreach($args as $key => $value){
            if(is_string($value)){
                $temp = array();
                foreach($arr as $k=> $v){
                    $temp[$k] = $v[$value];
                }
                $args[$key] = $temp;
            }
        }
        //引用值
        $args[] = &$arr;
        call_user_func_array('array_multisort',$args);
        return array_pop($args);
    }

    /**
     * 获取下个时间点的时间戳
     * 比如获取下个10点的时间戳
     */
    public static function getNextDayTimeStamp($hour) {
        $current_hour = intval(date('H', time()));

        if ($current_hour < $hour) {
            return strtotime(date('Y-m-d')) + $hour * 3600;
        }

        return strtotime(date('Y-m-d', strtotime("+1 day", time()))) + $hour * 3600;
    }

    /**
     * 额度向上去整千
     */
    public static function ceilByThousand($amount, $base = 1000)
    {
        if ($amount === 0) {
            return 0;
        }

        return $base * ceil($amount / $base);
    }

    /**
     * 数组按某个字段去重
     * @return float
     */
    public static function unique_multidim_array($array, $key) {
        $temp_array = array();
        $i = 0;
        $key_array = array();

        foreach($array as $val) {
            if (!in_array($val[$key], $key_array)) {
                $key_array[$i] = $val[$key];
                $temp_array[$i] = $val;
            }
            $i++;
        }
        return $temp_array;
    }
}
